package controller;

import jakarta.servlet.ServletContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

@Controller
@RequestMapping("/file")
public class UploadController {

    @Autowired
    private ServletContext application;

    @RequestMapping("/upload")
    public String upload(@RequestParam("name") String name,
                         @RequestParam("file") MultipartFile file) throws IOException {
        System.out.println("UploadController.upload()");

        System.out.println("name = " + name);
        System.out.println("file = " + file);

        System.out.println("file.getName() = " + file.getName());
        System.out.println("file.getOriginalFilename() = " + file.getOriginalFilename());
        System.out.println("file.getContentType() = " + file.getContentType());
        System.out.println("file.getSize() = " + file.getSize());

//        InputStream in=file.getInputStream();

//        Resource resource=file.getResource();

        String uploadDir=application.getRealPath("WEB-INF/upload");
        String fileName=file.getOriginalFilename();

        System.out.println("uploadDir = " + uploadDir);

        file.transferTo(new File(uploadDir,fileName));

        return "redirect:/showUpload";
    }
}
